package com.sxfq.loansupermarket.backsystem.modular.remoteSynergy.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.sxfq.loansupermarket.backsystem.common.constant.factory.PageFactory;
import com.sxfq.loansupermarket.backsystem.common.constant.tips.Tip;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.common.exception.BizExceptionEnum;

import com.sxfq.loansupermarket.backsystem.core.util.qr.ImgQrTool;

import java.io.File;
import java.util.HashMap;

import java.nio.file.Path;

import com.sxfq.loansupermarket.backsystem.common.persistence.model.User;
import com.sxfq.loansupermarket.backsystem.common.persistence.dao.UserMapper;
import com.sxfq.loansupermarket.backsystem.common.exception.BussinessException;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.DateTimeKit;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.core.util.StringUtil;
import com.sxfq.loansupermarket.backsystem.core.util.ToolUtil;
import com.sxfq.loansupermarket.backsystem.core.util.qr.QrImage;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.remoteSynergy.entity.*;
import com.sxfq.loansupermarket.backsystem.modular.remoteSynergy.service.ICaseSelectionUploadService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.sxfq.loansupermarket.backsystem.modular.remoteSynergy.service.ICaseSelectionManagementService;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;


/**
 * @author py
 * @Date
 */
@Controller
@RequestMapping("/caseSelectionUpload")
public class CaseSelectionUploadController extends BaseController {
    @Autowired
    ICaseSelectionUploadService service;

    @Autowired
    ICaseSelectionManagementService managementService;

    @Autowired
    private SqlMapper sqlMapper;


    @Autowired
    UserMapper userMapper;


    private String PREFIX = "/remoteSynergy/";

    private static String average = "6";

    /**
     * 跳转到病例上传查询
     */
    @RequestMapping("")
    public String to_caseSelectionUpload(Model model) {
        String tableHead = ShiroKit.getSessionAttr("abbreviation");
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        return PREFIX + "/case_selection_upload.html";
    }

    @RequestMapping(value = "/to_body_pulp_case_add")
    public String to_body_pulp_case_add(Model model) throws Exception {
        String tableHead = ShiroKit.getSessionAttr("abbreviation");
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String randomNumbersql = "select DATE_FORMAT(now(),'%Y%m%d%k%i%S') as randomNumber from dual";
        DaulInfo infos = sqlMapper.selectOne(randomNumbersql, DaulInfo.class);
        model.addAttribute("num", infos.getRandomNumber());
        return PREFIX + "/add/body_pulp_case_add.html";
    }

    @RequestMapping(value = "/to_body_pulp_case_view/{id}")
    public String to_body_pulp_case_view(@PathVariable String id, Model model) {
        String tableHead = ShiroKit.getSessionAttr("abbreviation");
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String sql = "select * from case_selection_information where id='" + id + "';";
        CaseSelectionUploadInfo caseSelectionUploadInfo = sqlMapper.selectOne(sql, CaseSelectionUploadInfo.class);
        String sql1 = "select * from case_selection_info where information_id='" + id + "' and judges='" + ShiroKit.getUser().getAccount() + "'" +
                " order by information_id limit 1;";
        if ("病例评选管理员".equals(ShiroKit.getUser().getRoleName())) {
            sql1 = "select * from case_selection_info where information_id='" + id + "' order by information_id limit 1;";
        }
        CaseSelectionUploadInfo caseSelectionUploadInfo1 = sqlMapper.selectOne(sql1, CaseSelectionUploadInfo.class);
        if (caseSelectionUploadInfo1 != null) {
            caseSelectionUploadInfo.setMark(caseSelectionUploadInfo1.getMark());
            caseSelectionUploadInfo.setCaseComment(caseSelectionUploadInfo1.getCaseComment());
        } else {
            caseSelectionUploadInfo.setMark("");
            caseSelectionUploadInfo.setCaseComment("");
        }
        String sql2 = "select * from case_selection_assistance_info where information_id='" + id + "';";
        List<CaseSelectionAssistanceInfo> info2 = sqlMapper.selectList(sql2, CaseSelectionAssistanceInfo.class);
        caseSelectionUploadInfo.setCaseSelectionAssistanceInfoList(info2);

        String sql4 = "select * from case_selection_tooth_site where information_id='" + id + "'";
        List<CaseSelectionToothSiteInfo> info4 = sqlMapper.selectList(sql4, CaseSelectionToothSiteInfo.class);
        caseSelectionUploadInfo.setCaseSelectionToothSiteInfoList(info4);

        String sql3 = " select * from case_selection_score_info where information_id='" + id + "';";
        List<CaseSelectionUploadInfo> selectionScoreInfoList = sqlMapper.selectList(sql3, CaseSelectionUploadInfo.class);
        String sqlrating = "select * from rating_items_info order by num asc;";
        List<RatingItemsInfo> ratingItemsInfoList = sqlMapper.selectList(sqlrating, RatingItemsInfo.class);
        model.addAttribute("ratingItemsInfoList", ratingItemsInfoList);
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        model.addAttribute("selectionScoreInfoList", selectionScoreInfoList);
        model.addAttribute("caseSelectionUploadInfo", caseSelectionUploadInfo);
        return PREFIX + "/view/body_pulp_case_view.html";
    }

    @RequestMapping(value = "/to_body_pulp_case_score/{id}")
    public String to_body_pulp_case_score(@PathVariable String id, Model model) {
        String tableHead = ShiroKit.getSessionAttr("abbreviation");
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String sql = "select * from case_selection_information where id='" + id + "';";
        CaseSelectionUploadInfo caseSelectionUploadInfo = sqlMapper.selectOne(sql, CaseSelectionUploadInfo.class);
        String sql1 = "select * from case_selection_info where information_id='" + id + "' and judges='" + ShiroKit.getUser().getAccount() + "'" +
                " order by information_id limit 1;";
        if ("病例评选管理员".equals(ShiroKit.getUser().getRoleName())) {
            sql1 = "select * from case_selection_info where information_id='" + id + "' " +
                    " order by information_id limit 1;";
        }
        CaseSelectionUploadInfo caseSelectionUploadInfo1 = sqlMapper.selectOne(sql1, CaseSelectionUploadInfo.class);
        if (caseSelectionUploadInfo1 == null) {
            caseSelectionUploadInfo.setMark("");
            caseSelectionUploadInfo.setCaseComment("");
        } else {
            caseSelectionUploadInfo.setMark(caseSelectionUploadInfo1.getMark());
            caseSelectionUploadInfo.setCaseComment(caseSelectionUploadInfo1.getCaseComment());
        }
        String sql2 = "select * from case_selection_assistance_info where information_id='" + id + "';";
        List<CaseSelectionAssistanceInfo> info2 = sqlMapper.selectList(sql2, CaseSelectionAssistanceInfo.class);
        caseSelectionUploadInfo.setCaseSelectionAssistanceInfoList(info2);

        String sql5 = "select * from case_selection_tooth_site where information_id='" + id + "';";
        List<CaseSelectionToothSiteInfo> info5 = sqlMapper.selectList(sql5, CaseSelectionToothSiteInfo.class);
        caseSelectionUploadInfo.setCaseSelectionToothSiteInfoList(info5);

        String sql3 = " select * from case_selection_score_info where information_id='" + id + "' and judges='" + ShiroKit.getUser().getAccount() + "';";
        if ("病例评选管理员".equals(ShiroKit.getUser().getRoleName())) {
            sql3 = " select * from case_selection_score_info where information_id='" + id + "';";
        }
        List<CaseSelectionUploadInfo> ratingItemsInfoList = sqlMapper.selectList(sql3, CaseSelectionUploadInfo.class);
        if (ratingItemsInfoList.size() > 0) {
            model.addAttribute("ratingItemsInfoList", ratingItemsInfoList);
        } else {
            String sqlrating = "select * from rating_items_info order by num asc;";
            ratingItemsInfoList = sqlMapper.selectList(sqlrating, CaseSelectionUploadInfo.class);
            model.addAttribute("ratingItemsInfoList", ratingItemsInfoList);
        }
        String sql4 = "select " +
                " (" +
                " CASE t.type_icon " +
                "  WHEN 'uploader-demo4' THEN " +
                "   '术前' " +
                "  WHEN 'uploader-demo9' THEN " +
                "   '术中' " +
                "  WHEN 'uploader-demo8' THEN " +
                "   '术后' " +
                "  END " +
                "  ) as photoType,t.* from case_selection_intelligent_score_assistance_info t where information_id='" + id + "' " +
                " order by t.type_icon='uploader-demo8',t.type_icon='uploader-demo9',t.type_icon='uploader-demo4';";
        List<CaseSelectionIntelligentScoreAssistanceInfo> info4 = sqlMapper.selectList(sql4, CaseSelectionIntelligentScoreAssistanceInfo.class);
        caseSelectionUploadInfo.setCaseSelectionIntelligentScoreAssistanceInfoList(info4);
        if (ShiroKit.getSessionAttr("explanationInfoList") == null) {
            String getListSql = "select id as id, label as label, content as content, num as num from case_selection_explanation_info order by num;";
            List<ExplanationInfo> explanationInfoList = sqlMapper.selectList(getListSql, ExplanationInfo.class);
            ShiroKit.setSessionAttr("explanationInfoList", explanationInfoList);
        }
        model.addAttribute("explanationInfoList", ShiroKit.getSessionAttr("explanationInfoList"));
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        model.addAttribute("caseSelectionUploadInfo", caseSelectionUploadInfo);
        if ("病例评选管理员".equals(ShiroKit.getUser().getRoleName())) {
            return PREFIX + "/view/body_pulp_case_views.html";
        } else {
            return PREFIX + "/view/body_pulp_case_score.html";
        }
    }

    @RequestMapping(value = "/getMaxUpload", method = RequestMethod.POST)
    @ResponseBody
    public String getMaxUpload() {
        String sql = "select * from max_case_submit_info limit 1";
        String sql1 = "select count(1) as caseCount from case_selection_information where applyer='" + ShiroKit.getUser().getAccount() + "' and save_status=1";
        RatingItemsInfo ratingItemsInfo1 = sqlMapper.selectOne(sql, RatingItemsInfo.class);
        RatingItemsInfo ratingItemsInfo2 = sqlMapper.selectOne(sql1, RatingItemsInfo.class);
        if (ratingItemsInfo2.getCaseCount() == ratingItemsInfo1.getMaxNum()) {
            return ratingItemsInfo1.getMaxNum() + "";
        } else {
            return "aa";
        }
    }

    @RequestMapping(value = "/getCaseQRCode", method = RequestMethod.POST)
    @ResponseBody
    public String getCaseQRCode(String id) {
//        final int width = 300;
//        final int height = 300;
//        final String format = "png";
//        final String text = "http://www.yiyatest.cn:8070/CRMS/caseSelectionVote";
//        //定义二维码的参数
//        HashMap hints = new HashMap();
//        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
//        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
//        hints.put(EncodeHintType.MARGIN, 2);
        try { // 生成二维码
//            BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
//            Path file = new File("D:\\201903071\\apache-tomcat-8.0.30\\webapps\\ROOT/wdyltblpx_img.png").toPath();
//            MatrixToImageWriter.writeToPath(bitMatrix, format, file);
            QrImage para = new QrImage.Builder()
                    .setFileOutputPath("D:\\201903071\\apache-tomcat-8.0.30\\webapps\\ROOT/wdyltblpx_tpimg.png")
                    .setQrContent("http://www.yiyatest.cn:8069/WDYLT/caseSelectionVote")
                    .setQrHeight(300)
                    .setQrWidth(300)
                    .setQrIconFilePath("D:\\201903071\\apache-tomcat-8.0.30\\webapps\\ROOT/y46.png")
                    .setTopWrodHeight(100)
                    .setWordContent("武大医联体优秀病例评选投票")
                    .setWordSize(18).build();
            ImgQrTool.createQrWithFontsAbove(para);
//            Runtime.getRuntime().exec(new String[]{"cmd.exe", "/c", "D:\\201903071\\apache-tomcat-8.0.30\\webapps\\ROOT/wdyltblpx_img.png"});
        } catch (Exception e) {
        }
        return "wdyltblpx_tpimg.png";
    }


    @RequestMapping(value = "/updatePassWord", method = RequestMethod.POST)
    @ResponseBody
    public String updatePassWord() {
        Integer id = ShiroKit.getUser().getId();
        User user = userMapper.selectById(id);
        String newPassWord = super.getPara("newPassWord").trim();
        String passWord = super.getPara("passWord").trim();
        String passWordMd5 = ShiroKit.md5(passWord, user.getSalt());
        if (passWordMd5.equals(user.getPassword())) {
            String newPassWordMd5 = ShiroKit.md5(newPassWord, user.getSalt());
            user.setPassword(newPassWordMd5);
            userMapper.updateById(user);
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "0";
        } else {
            return "1";
        }
    }

    @RequestMapping(value = "/to_body_pulp_case_open/{id}")
    public String to_body_pulp_case_open(@PathVariable String id, Model model) {
        String tableHead = ShiroKit.getSessionAttr("abbreviation");
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String sql = "select * from case_selection_information where id='" + id + "';";
        CaseSelectionUploadInfo caseSelectionUploadInfo = sqlMapper.selectOne(sql, CaseSelectionUploadInfo.class);
        String sql1 = "select * from case_selection_info where information_id='" + id + "' and judges='" + ShiroKit.getUser().getAccount() + "'" +
                " order by information_id limit 1;";
        if ("病例评选管理员".equals(ShiroKit.getUser().getRoleName())) {
            sql1 = "select * from case_selection_info where information_id='" + id + "' " +
                    " order by information_id limit 1;";
        }
        CaseSelectionUploadInfo caseSelectionUploadInfo1 = sqlMapper.selectOne(sql1, CaseSelectionUploadInfo.class);
        if (caseSelectionUploadInfo1 == null) {
            caseSelectionUploadInfo.setMark("");
            caseSelectionUploadInfo.setCaseComment("");
        } else {
            caseSelectionUploadInfo.setMark(caseSelectionUploadInfo1.getMark());
            caseSelectionUploadInfo.setCaseComment(caseSelectionUploadInfo1.getCaseComment());
        }
        String sql2 = "select * from case_selection_assistance_info where information_id='" + id + "';";
        List<CaseSelectionAssistanceInfo> info2 = sqlMapper.selectList(sql2, CaseSelectionAssistanceInfo.class);
        caseSelectionUploadInfo.setCaseSelectionAssistanceInfoList(info2);
        String sql3 = " select * from case_selection_score_info where information_id='" + id + "';";
        List<CaseSelectionUploadInfo> ratingItemsInfoList = sqlMapper.selectList(sql3, CaseSelectionUploadInfo.class);
        if (ratingItemsInfoList.size() > 0) {
            model.addAttribute("ratingItemsInfoList", ratingItemsInfoList);
        } else {
            String sqlrating = "select * from rating_items_info order by num asc;";
            ratingItemsInfoList = sqlMapper.selectList(sqlrating, CaseSelectionUploadInfo.class);
            model.addAttribute("ratingItemsInfoList", ratingItemsInfoList);
        }
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        model.addAttribute("caseSelectionUploadInfo", caseSelectionUploadInfo);
        model.addAttribute("caseScorebyJudges", caseSelectionUploadInfo1.getSelectionScore());
        return PREFIX + "/view/body_pulp_case_open.html";
    }

    @RequestMapping(value = "/to_body_pulp_case_update/{id}")
    public String to_body_pulp_case_update(@PathVariable String id, Model model) {
        String tableHead = ShiroKit.getSessionAttr("abbreviation");
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String sql = "select * from case_selection_information where id='" + id + "';";
        CaseSelectionUploadInfo caseSelectionUploadInfo = sqlMapper.selectOne(sql, CaseSelectionUploadInfo.class);
        String sql2 = "select * from case_selection_assistance_info where information_id='" + id + "' ";
        List<CaseSelectionAssistanceInfo> info2 = sqlMapper.selectList(sql2, CaseSelectionAssistanceInfo.class);
        caseSelectionUploadInfo.setCaseSelectionAssistanceInfoList(info2);
        String sql3 = "select * from case_selection_tooth_site where information_id='" + id + "'";
        List<CaseSelectionToothSiteInfo> info3 = sqlMapper.selectList(sql3, CaseSelectionToothSiteInfo.class);
        caseSelectionUploadInfo.setCaseSelectionToothSiteInfoList(info3);
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        model.addAttribute("caseSelectionUploadInfo", caseSelectionUploadInfo);
        return PREFIX + "/update/body_pulp_case_update.html";
    }

    /**
     * 删除牙体牙髓病例
     */
    @RequestMapping(value = "/deleteBodyPulpCase/{id}")
    @ResponseBody
    public Tip deleteBodyPulpCase(@PathVariable String id) throws Exception {
        service.deleteBodyPulpCase(id);
        return SUCCESS_TIP;
    }

    /**
     * 病例上传管理列表
     */
    @RequestMapping("/list")
    @ResponseBody
    public Object getInfoList(SearchCaseSelectionUploadInfo info, HttpServletRequest request) {
        Page<CaseSelectionUploadInfo> page = new PageFactory<CaseSelectionUploadInfo>().defaultPage();
        try {
            if (info != null) {
                if (info.getIsUpload() == 2) {
                    info.setStartIndex(page.getSize() * (page.getCurrent() - 1));
                    info.setLimitIndex(page.getSize());
                    page.setCurrent(0);
                    List<CaseSelectionUploadInfo> list = service.selectPageListByQueryGetGoBack(page, info);
                    if (list.size() == 0) {
                        info.setStartIndex(0);
                        list = service.selectPageListByQueryGetGoBack(page, info);
                    }
                    page.setTotal(service.getByQueryGetGoBackPagesCount(page, info));
                    page.setRecords(list);
                } else {
                    info.setStartIndex(page.getSize() * (page.getCurrent() - 1));
                    info.setLimitIndex(page.getSize());
                    page.setCurrent(0);
                    List<CaseSelectionUploadInfo> list = service.selectPageListByQueryGetMap(page, info);
                    if (list.size() == 0) {
                        info.setStartIndex(0);
                        list = service.selectPageListByQueryGetMap(page, info);
                    }
                    page.setTotal(service.getQueryPagesCount(page, info));
                    page.setRecords(list);
                }
            } else {
                info.setStartIndex(page.getSize() * (page.getCurrent() - 1));
                info.setLimitIndex(page.getSize());
                page.setCurrent(0);
                List<CaseSelectionUploadInfo> list = service.selectPageListByQueryGetMap(page, info);
                if (list.size() == 0) {
                    info.setStartIndex(0);
                    list = service.selectPageListByQueryGetMap(page, info);
                }
                page.setTotal(service.getQueryPagesCount(page, info));
                page.setRecords(list);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.packForBT(page);
    }

    /**
     * 病例上传统计数量
     */
    @RequestMapping("/statistics")
    @ResponseBody
    public List<TongJiInfo> statistics(SearchCaseSelectionUploadInfo searchInfo, HttpServletRequest request) {
        return service.statistics(searchInfo);
    }

    /**
     * 创建时暂存病例
     */
    @RequestMapping(value = "/storage")
    @ResponseBody
    public int storage(@Valid CaseSelectionUploadInfo info, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        info.setSaveStatus(0);
        info.setApplyer("");
        return service.insert(info);
    }

    /**
     * 暂存修改病例
     */
    @RequestMapping(value = "/updatestorage")
    @ResponseBody
    public int updatestorage(@Valid CaseSelectionUploadInfo info, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        info.setSaveStatus(0);
        info.setApplyer("");
        return service.update(info);
    }

    /**
     * 提交修改病例
     */
    @RequestMapping(value = "/updateSubmitTo")
    @ResponseBody
    public int updateSubmitTo(@Valid CaseSelectionUploadInfo info, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sql = "select id,max_num as maxNum,remarks as remarks,backup2 as backup2 from max_case_submit_info limit 1";
        RatingItemsInfo ratingItemsInfo1 = sqlMapper.selectOne(sql, RatingItemsInfo.class);

        String sql1 = "select count(1) as caseCount from case_selection_information where applyer='" + ShiroKit.getUser().getAccount() + "' and save_status=1";
        RatingItemsInfo ratingItemsInfo2 = sqlMapper.selectOne(sql1, RatingItemsInfo.class);
        if (ratingItemsInfo2.getCaseCount() == ratingItemsInfo1.getMaxNum()) {
            return ratingItemsInfo1.getMaxNum();
        } else {
            info.setSaveStatus(1);
            info.setApplyTime(DateTimeKit.now());
            info.setApplyer(ShiroKit.getUser().getName());
            service.update(info);
            return 10001;
        }
    }

    /**
     * 创建时提交病例
     */
    @RequestMapping(value = "/submitTo")
    @ResponseBody
    public int submitTo(@Valid CaseSelectionUploadInfo info, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sql = "select * from max_case_submit_info limit 1";
        String sql1 = "select count(1) as caseCount from case_selection_information where applyer='" + ShiroKit.getUser().getAccount() + "' and save_status=1";
        RatingItemsInfo ratingItemsInfo1 = sqlMapper.selectOne(sql, RatingItemsInfo.class);
        RatingItemsInfo ratingItemsInfo2 = sqlMapper.selectOne(sql1, RatingItemsInfo.class);
        if (ratingItemsInfo2.getCaseCount() == ratingItemsInfo1.getMaxNum()) {
            return ratingItemsInfo1.getMaxNum();
        } else {
            info.setSaveStatus(1);
            info.setApplyTime(DateTimeKit.now());
            info.setApplyer(ShiroKit.getUser().getName());
            service.insert(info);
            return 10001;
        }
    }

    /**
     * 上传图片(上传到项目的webapp/static/img)
     */
    @RequestMapping(method = RequestMethod.POST, path = "/upLoadProcess/{cri}")
    @ResponseBody
    public String upLoadProcess(@RequestPart("file") MultipartFile picture,
                                @PathVariable String cri) {
        String id = cri.split(",")[0];
        if (("aa").equals(id)) {  //病历id是空，先上传图片了，先不插入病历id
            id = null;
        }
        String typeName = cri.split(",")[1];
        String num = cri.split(",")[2];
        if (("111").equals(num)) {
            num = null;
        }
        String realPath = "D:\\201903071\\apache-tomcat-8.0.30\\webapps\\ROOT\\yingxiang";
        String httpUrl = "http://47.98.150.186:8070/yingxiang/";
        String imageurl = httpUrl + "\\" + picture.getOriginalFilename();
        try {
            FileUtils.copyInputStreamToFile(picture.getInputStream(), new File(realPath, picture.getOriginalFilename()));
            String sql = "insert into case_selection_assistance_info (information_id,type_icon,create_time,update_time," +
                    "image_path,treatment_steps,num) values " +
                    "('" + id + "','" + typeName + "','" + DateTimeKit.now() + "','" + DateTimeKit.now() + "','" + imageurl + "',''," + num + ")";
            sqlMapper.insert(sql);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return realPath;
    }

    //删除图片
    @RequestMapping(value = "/delteProcess", method = RequestMethod.POST)
    @ResponseBody
    public int delteProcess(String id, String customerId) throws Exception {
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sql = "delete from case_selection_assistance_info where id='" + id + "'";
        return sqlMapper.delete(sql);
    }

    //获取 图片
    @RequestMapping(value = "/getImg", method = RequestMethod.POST)
    @ResponseBody
    public List<CaseSelectionAssistanceInfo> getImg(String num, String typeIcon, String informationId) throws Exception {
        if (StringUtil.isNotEmpty(informationId)) {
            String sql = "select * from case_selection_assistance_info where information_id='" + informationId + "' and type_icon='" + typeIcon + "'";
            List<CaseSelectionAssistanceInfo> info2 = sqlMapper.selectList(sql, CaseSelectionAssistanceInfo.class);
            return info2;
        } else {
            String sql = "select * from case_selection_assistance_info where num='" + num + "' and type_icon='" + typeIcon + "' ";
            List<CaseSelectionAssistanceInfo> info2 = sqlMapper.selectList(sql, CaseSelectionAssistanceInfo.class);
            return info2;
        }
    }

    @RequestMapping("/doctor_caseScore/{id}")
    public String doctor_caseScore(@PathVariable String id, Model model) {
        String tableHead = ShiroKit.getSessionAttr("abbreviation");
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String sql = "select * from rating_items_info where information_id='" + id + "'";
        List<RatingItemsInfo> ratingItemsInfoList = sqlMapper.selectList(sql, RatingItemsInfo.class);
        model.addAttribute("ratingItemsInfoList", ratingItemsInfoList);
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        return PREFIX + "/doctor_caseScore.html";
    }

    @RequestMapping("/doctor_caseMarking")
    public String doctor_caseMarking(Model model) {
        String tableHead = ShiroKit.getSessionAttr("abbreviation");
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        return PREFIX + "/doctor_caseMarking.html";
    }

    @RequestMapping("/scoreCase")
    @ResponseBody
    public int scoreCase() {
        String sql = "update case_selection_information a set a.case_score=IFNULL((select sum(b.selection_score)/(select count(distinct(judges)) " +
                "from case_selection_info) from case_selection_info b where a.id=b.information_id group by b.information_id),0.00)," +
                "selection_status=1,selection_time='" + DateTimeKit.now() + "'";
        return sqlMapper.update(sql);
    }

    /**
     * @param
     * @return
     */
    @RequestMapping("/allocationCases")
    @ResponseBody
    public String allocationCases() {
        List<String> caseIdlist = managementService.getAllCasesIds();
        List<String> expertIdlist = managementService.getAllExpertIds();
        String expertId = "";
        if (caseIdlist != null && expertIdlist != null && caseIdlist.size() > 0 && expertIdlist.size() > 0) {
            //如果病例总数小于规定值，每个医生都要审核所有病例,否则出了按规定值，
            String[] ids = new String[caseIdlist.size()];
            ids = caseIdlist.toArray(ids);
            for (int i = 0; i < expertIdlist.size(); i++) {
                expertId = expertIdlist.get(i);
                managementService.insertExpertAndCase(expertId, ids);
            }
            ids = new String[caseIdlist.size()];
            ids = caseIdlist.toArray(ids);
            managementService.updateCasesForDistribution(ids);
        }
        return "success";
    }
}